//
//  LogCatDelegateHelper.m
//  LogCat
//
//  Created by 清风徐来 on 2023/12/15.
//

#import "LogCatDelegateHelper.h"
#import <LogCat/LogCatManager.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#include <ifaddrs.h>
#include <arpa/inet.h>

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
@implementation LogCatDelegateHelper

/// 打开链接
/// - Parameter url: 链接地址
+(BOOL)handleOpenURL:(NSURL *)url {
    return [self handleOpenURL:url withSuccessBlock:nil];
}

/// 打开链接
/// - Parameter url: 链接地址
/// - Parameter successBlock: 回调
+(BOOL)handleOpenURL:(NSURL *)url withSuccessBlock:(_Nullable HandUrlResultBlock)successBlock {
    NSString *urlString = [self decodedString:url.absoluteString];
    NSString *scheme = [[LogCatManager shared] getScheme];
    BOOL isSuccess = false;
    NSString *resutMsg = @"支付失败";

    if ([self func_containsString:urlString compareString:scheme]) {
        NSString *drag = [[urlString componentsSeparatedByString:@"?"] lastObject];
        NSDictionary *page = [self dictionaryWithString:drag];
        NSDictionary *memoDic = page[@"memo"];
        NSString *resultStatus = [memoDic objectForKey:@"ResultStatus"];

        if ([resultStatus isEqualToString:@"9000"]) {
            resutMsg = @"支付成功";
            isSuccess = true;
        }else if ([resultStatus isEqualToString:@"6001"]) {
            resutMsg = @"支付取消";
        }
    }
    return isSuccess;
}

/// 判断字符中是否包含另一个字符
/// - Parameters:
///   - string: 字符
///   - compareStrong: 待判断的字符
+(BOOL)func_containsString:(NSString *)string compareString:(NSString *)compareStrong {
    if(string == nil) return NO;
    return [string rangeOfString:compareStrong].location != NSNotFound;
}

/// DeCode URL
/// - Parameter urlString: urlString description
+(NSString *)decodedString:(NSString *)urlString {
    NSString *timer = urlString;
    NSString *suspension=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)timer, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return suspension;
}

/// 字符转字典
/// - Parameter jsonString: jsonString description
+(NSDictionary *)dictionaryWithString:(NSString *)jsonString {
    NSData *request = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    return [NSJSONSerialization JSONObjectWithData:request options:NSJSONReadingMutableLeaves error:nil];
}

/// 打开指定链接
/// - Parameter url: url description
+ (void)openLinkWithURL:(NSURL *)url {
    if (@available(iOS 10.0, *)) {
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                if (success) {
                    NSLog(@"Open url success");
                }
            }];
        }else {
            NSLog(@"无法打开链接");
        }
    }else {
        [[UIApplication sharedApplication] openURL:url];
    }
}

/// 获取IP地址
+ (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;

    // 获取所有接口的列表
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // 遍历列表找到首个IPv4地址（排除本地回环地址127.0.0.1）
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if (temp_addr->ifa_addr->sa_family == AF_INET) {
                // 检查接口是否en0（Wi-Fi）
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // 获取IPv4地址
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }

    // 释放内存
    freeifaddrs(interfaces);
    return address;
}

/// 检测IP
/// - Parameter completion: 回调
+ (void)checkIfIPisFromChinaWithCompletion:(void (^)(BOOL isInChina))completion {
    // 第一步：获取公网 IP 地址
    NSURL *url = [NSURL URLWithString:@"https://api.ipify.org?format=json"];
    [[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSString *ipAddress = json[@"ip"];
            // 第二步：使用 IP 地址查询地理位置
            [self queryGeoLocationForIP:ipAddress completion:completion];
        }
    }] resume];
}

/// 检测IP位置
/// - Parameter completion: 回调
+ (void)queryGeoLocationForIP:(NSString *)ipAddress completion:(void (^)(BOOL isInChina))completion {
    NSString *urlString = [NSString stringWithFormat:@"http://ip-api.com/json/%@", ipAddress];
    NSURL *url = [NSURL URLWithString:urlString];

    [[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            //            NSLog(@"json = %@", json);
            NSString *country = json[@"country"];
            BOOL isInChina = [country isEqualToString:@"China"];
            if (completion) {
                completion(isInChina);
            }
        } else {
            if (completion) {
                completion(NO);
            }
        }
    }] resume];
}


@end
#pragma clang diagnostic pop
